package jsu.yym.tiktok.controller;

import jsu.yym.tiktok.pojo.Fans;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.mapper.FansMapper;
import jsu.yym.tiktok.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
public class fansController {
    @Autowired
    private FansMapper fansMapper;
    @Autowired
    private UserMapper userMapper;

    //获取用户的关注列表
    @GetMapping("/person/get")
    public ResponseResult getPerson()
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        //获取所有关注的人的id
        List<String> fans = fansMapper.getPersonIdsByUsername(id);
        if(fans.isEmpty())
            return new ResponseResult(409,"暂时还没关注别人");
        //根据idList获取所有的User对象
        List<User> users = userMapper.getUsersByUsernames(fans);
        return new ResponseResult(200,"获取成功",users);
    }

    //获取用户的粉丝列表
    @GetMapping("/fans/get")
    public ResponseResult getFans()
    {
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        //获取所有关注的人的id
        List<String> fans = fansMapper.getFansByUsername(id);
        //根据idList获取所有的User对象
        List<User> users = userMapper.getUsersByUsernames(fans);
        if (Objects.isNull(users)) {
            return new ResponseResult(409,"暂时还没有粉丝");
        }
        return new ResponseResult(200,"获取成功",users);
    }

    //新增关注
    @PostMapping("/fans/add/{personId}")
    public ResponseResult addFans(@PathVariable String personId){
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        Fans fans = new Fans(id,personId);
       fansMapper.insert(fans);
        return new ResponseResult(200,"关注成功");
    }

    //取消关注||移除粉丝
    @PostMapping("/fans/delete/{personId}")
    public ResponseResult deleteFans(@PathVariable String personId){
        String id = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null)
            id = authentication.getName(); // 获取当前用户的id
        Fans fans = new Fans(id,personId);
        int count = fansMapper.deleteById(fans);
        if (count<=0)
            return new ResponseResult(503,"取消失败");
        return new ResponseResult(200,"取消成功");
    }



}
